
#ifndef __KEY_TABLE_VIEW_H
#define __KEY_TABLE_VIEW_H

#include "../crypt/AbstractKey.h"
#include "Key.h"

class KeyDB;

/** An interface to interact with a single table of keys with
 * consistent uses. */
class KeyTableView
{
   public:
      KeyTableView(KeyDB *nkdb, Key::keypurposetype ikeytableusetype,
                   const char *itablename, const char *itableWIPpwd,
                   const char *iresidentkeyname, const char *iresidentkeypwd);
      ~KeyTableView();
      int testKeyExists(const char *keyname) const;
      char *getKeyOwner(const char *keyname) const;
      void deleteKey(const char *keyname) const;
      int countKeyChainOfOwner(const char *owner) const;
      char *getLatestKeyNameOfOwner(const char *owner) const;
      void retryGettingOwnKeys(const char *ownpwd);
      void updateToLatestOwnKey(const char *ownpwd);
      int updateKeyChainUsingFile(const char *key_filename, const char *WIPpwd, apr_pool_t *mp);
      int isGeneratingNewOwnKeysAcceptable() const { return couldgeneratekeysflag; }
      /** Get constant WIP password. */
      const char *getWIPPassword() const { return tableWIPpwd; }
      /** Get own key. */
      const AbstractKey *getOwnKey() const { return ownkey; }
      /** Has own key. */
      const bool hasOwnKey() const { return (ownkey != NULL); }
      void decrementKeyExistsReferenceCount(const char *keyname) const;
      void incrementKeyExistsReferenceCount(const char *keyname) const;
      int getKeyExistsReferenceCount(const char *keyname) const;
      void decrementKeyUsedReferenceCount(const char *keyname) const;
      void incrementKeyUsedReferenceCount(const char *keyname) const;
      int getKeyUsedReferenceCount(const char *keyname) const;
   protected:
      /** Pointer to the key database, needed to interact with the
       * actual SQL database. */
      KeyDB *nkeydb;
      /** A flag denoting the use scenario for keys in this table.
       * One of KeyTableView::keytableusetype. */
      Key::keypurposetype keytableusetype;
      /** The name of the table that this view interfaces with. */
      char *tablename;
      /** The work-in-progress password used for this table. */
      char *tableWIPpwd;
      /** The name of the resident key that defines the identity of
       * the main actor. */
      char *residentkeyname;
      /** The key from this table that defines the identity of the
       * main actor (for the given key purpose of this database). */
      AbstractKey *ownkey;
      /** Whether it is permissible to generate new keys on a failure.
       * This is set when there are no keys, and unset when there are
       * keys present.  Checking this before regenerating keys
       * prevents overwriting of keys by unauthorised users. */
      int couldgeneratekeysflag;
};

// Could add EncryptionKeyTable, DecryptionKeyTable etc...

#endif
